import { Icon } from 'element-react';
import { useMemo } from 'react';
import MdPreview from './MdPreview.js';

const MdRenderer = ({
    source = '',
    inner_suffix = false,
    sendMessage,
    child_node,
    chat_record_id,
    runtime_node_id,
    disabled = false,
    icon
}) => {
    const split_quick_question = (result) => {
        return result
          .map((item) => split_quick_question_(item))
          .reduce((x, y) => {
                return [...x, ...y];
            }, []);
    };

    const split_quick_question_ = (source) => {
        const temp_md_quick_question_list = source.match(/<quick_question>[\d\D]*?<\/quick_question>/g);
        const md_quick_question_list = temp_md_quick_question_list
           ? temp_md_quick_question_list.filter((i) => i)
            : [];
        const split_quick_question_value = source
          .split(/<quick_question>[\d\D]*?<\/quick_question>/g)
          .filter((item) => item!== undefined)
          .filter((item) =>!md_quick_question_list?.includes(item));
        const result = Array.from(
            { length: md_quick_question_list.length + split_quick_question_value.length },
            (v, i) => i
        ).map((index) => {
            if (index % 2 === 0) {
                return { type: 'md', content: split_quick_question_value[Math.floor(index / 2)] };
            } else {
                return {
                    type: 'question',
                    content: md_quick_question_list[Math.floor(index / 2)]
                      .replace('<quick_question>', '')
                      .replace('</quick_question>', '')
                };
            }
        });
        return result;
    };

    const md_view_list = useMemo(() => {
        const temp_source = source;
        return split_quick_question([temp_source]);
    }, [source]);
    return (
        <>
            {md_view_list.map((item, index) => (
                <div key={index}>
                    {item.type === 'question' ? (
                        <div
                            onClick={() => sendMessage? sendMessage(item.content, 'new') : () => {}}
                            className={`problem-button ellipsis-2 mt-4 mb-4 ${sendMessage? 'cursor' : 'disabled'}`}
                        >
                            <Icon name="edit"></Icon>
                            {item.content}
                        </div>
                    ) : (
                        <MdPreview
                            noIconfont
                            editorId="preview-only"
                            modelValue={item.content}
                            icon={icon}
                            className="zxkb-md"
                        />
                    )}
                </div>
            ))}
        </>
    );
};

export default MdRenderer;